package com.diy.sigmund.diycommon.spring.extensionpoint;

import com.diy.sigmund.diycommon.spring.extensionpoint.event.EmailEvent;
import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author ylm-sigmund
 * @since 2022/9/20 17:28
 */
@Order(1)
@Component
public class CustomBeanNameAware implements BeanNameAware, InitializingBean, SmartInitializingSingleton, CommandLineRunner,
        DisposableBean, ApplicationListener {

    private static final Logger log = LoggerFactory.getLogger(CustomBeanNameAware.class);
    private String beanName;

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
        log.info("[BeanNameAware] setBeanName = " + name);
    }

    @PostConstruct
    public void doSome() {
        log.info("[@PostConstruct] doSome");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("[InitializingBean] afterPropertiesSet");
    }

    @Override
    public void afterSingletonsInstantiated() {
        log.info("[SmartInitializingSingleton] afterSingletonsInstantiated");
    }

    /**
     * <br>使用@Order标识执行顺序
     * <br>容器启动成功后的最后一次回调
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("[CommandLineRunner] run");
    }

    @Override
    public void destroy() throws Exception {
        log.info("[DisposableBean] destroy");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        log.debug("[ApplicationListener] onApplicationEvent");
        if (event instanceof EmailEvent) {
            EmailEvent emailEvent = (EmailEvent) event;
            log.info("emailEvent:{}", JacksonUtil.toJson(emailEvent));
        } else {
            log.debug("容器本身事件:{}", event);
        }
    }

}
